{% load static %}
{% load bootstrap3  %}
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>
            {% block title %}Scirius - {{ path_info|title }}{% endblock %}
        </title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- Latest compiled and minified CSS -->
        <link rel="stylesheet"
              type="text/css"
              href="{% static 'django_tables2/themes/paleblue/css/screen.css' %}"/>
        <link rel="shortcut icon" href="{% static 'rules/favicon.ico' %}" />
        <script src="{% static 'dist/scirius-bundle.js' %}"></script>
        {% block head %}{% endblock %}
        <link rel="stylesheet"
              type="text/css"
              href="{% static 'dist/styles.css' %}"/>
    </head>
    <body>
        <meta charset="utf-8">
        <style>

.link {
  stroke-opacity: 0.6;
}

.node circle {
  stroke: #fff;
  stroke-width: 1.5px;
}

        </style>
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-12">
                    <div class="pull-left">
                        <form class="form" method="post">
                            {% csrf_token %}
                            <span class="glyphicon glyphicon-search">
                                Filter:
                                <input type="text"
                                       name="filter"
                                       id="id_filter"
                                       {% if filter %}
                                               value="{{ filter }}"
                                                             {% endif %}
                                       width="20"/>
                            </span>
                        </form>
                    </div>
                    <div class="pull-right">
                        <div class="btn-group">
                            Time: {% now "H:i:s" %} | Reload every {{ reload }}s
                            <a class="dropdown-toggle"
                               type="button"
                               id="display_reload"
                               data-toggle="dropdown">
                                <span class="glyphicon glyphicon-refresh"></span>
                            </a>
                            <ul class="dropdown-menu" id="display_reload">
                                <li>
                                    <a href="?reload=30">30s</a>
                                </li>
                                <li>
                                    <a href="?reload=60">1m</a>
                                </li>
                                <li>
                                    <a href="?reload=120">2m</a>
                                </li>
                                <li>
                                    <a href="?reload=300">5m</a>
                                </li>
                                <li>
                                    <a href="?reload=600">10m</a>
                                </li>
                            </ul>
                        </div>
                        <div class="btn-group">
                            | Last {{ date }}
                            <a class="dropdown-toggle"
                               type="button"
                               id="display_menu"
                               data-toggle="dropdown">
                                <span class="glyphicon glyphicon-cog"></span>
                            </a>
                            <ul class="dropdown-menu" id="display_menu">
                                <li>
                                    <a href="?duration=1">Last 1h</a>
                                </li>
                                <li>
                                    <a href="?duration=6">Last 6h</a>
                                </li>
                                <li>
                                    <a href="?duration=24">Last 24h</a>
                                </li>
                                <li>
                                    <a href="?duration=48">Last 2d</a>
                                </li>
                                <li>
                                    <a href="?duration=168">Last 7d</a>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-7">
                    <h2 class="title">
                        Source and Target
                    </h2>
                    <div >
                        <svg width="1100" height="750" id="alerts">
                        </svg>
                        <div id="highlight_info"></div>
                    </div>
                </div>
                <div class="col-md-5">
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-md-12">
                                <h2 class="title">
                                    Alert timeline
                                </h2>
                                <div id="timeline">
                                    <p>
                                        Fetching data...
                                    </p>
                                    <svg style="width:100%;height:300px">
                                    </svg>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <h2 class="title">Rule Activity</h2>
                                <div id="rules_table">Fetching data...</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <script>

$( 'document' ).ready(function () { draw_timeline({{ from_date }}, [{% autoescape off %} {{ probes|join:',' }} {% endautoescape %}], "{{ filter }}", 'Hits'); });

function differentiate_suppressed() {
    var suppressed_rules = [{{ suppressed }}];
    $("td.sid").each(
        function() {
            if (jQuery.inArray(parseInt($( this ).text(), 10), suppressed_rules) != -1) {
                $( this ).addClass("suppressed");
            }
        }
    );
}

{% if perms.rules.events_view %}
    {% if filter and not filter == "*" %}
$( 'document' ).ready(load_rules({{ from_date }},  [ '*' ], "{{ filter }}", differentiate_suppressed));
    {% else %}
$( 'document' ).ready(load_rules({{ from_date }},  [ '*' ], null, differentiate_suppressed));
    {% endif %}
{% endif %}

function draw_ippair_alerts(from_date, hosts, filter, callback) {
    esurl = "/rest/rules/es/ip_pair_network_alerts/?from_date=" + from_date + "&hosts=" + hosts.join()
    if (filter) {
        esurl = esurl + "&filter=" + filter;
    }
    $.ajax(
     {
     type:"GET",
     url:esurl,
     success: function(json) {
        if (json == null) {
             d3.select("svg#alerts").append('text').text("Error: no data to build the graph.")
             .attr("x", 150)
             .attr("y", 150);
            return;
        }
        if (json.links.length == 0) {
             d3.select("svg#alerts").append('text').text("No data to build the graph.")
             .attr("x", 150)
             .attr("y", 150);
             d3.select("svg#alerts").append('text').text("This dashboard needs signatures using target keyword as well as network info setup.")
             .attr("x", 30)
             .attr("y", 180);
            return;
        }

        var svg = d3.select("svg#alerts"),
            width = +svg.attr("width"),
            height = +svg.attr("height");

        var color = d3.scale.category20();

        var force = cola.d3adaptor(d3).linkDistance(100).size([width, height]);

        var groupMap = {};
        json.nodes.forEach(function (v, i) {
            var g = v.group;
            if (typeof groupMap[g] == 'undefined') {
                groupMap[g] = [];
            }
            groupMap[g].push(i);
	    if (v.group == "Internet") {
               v.width = v.height = 5;
	    } else {
               v.width = v.height = 30;
	    }
        });

        var groups = [];
        for (var g in groupMap) {
            groups.push({ id: g, leaves: groupMap[g] });
        }

        difflengths = 10 * 3 / Math.log10(json.nodes.length);
        force.nodes(json.nodes)
          .links(json.links)
          .groups(groups)
          .symmetricDiffLinkLengths(difflengths)
          .avoidOverlaps(true)
          .start(10,15,20);
/*
        var group = svg.selectAll('.group')
            .data(groups).enter().append('g');
*/
        var color_index = 0;
        var group = svg.selectAll('.group')
            .data(groups).enter().append('rect').classed('group', true)
            .attr('rx',5)
            .attr('ry',5)
            .style("fill", function (d) { return color(color_index++) ;})
            .call(force.drag);

        var tgroup = svg.selectAll('g.group')
            .data(groups).enter().append('text').classed('group', true)

	    .attr("dy", ".35em")
	    .text(function (d) { return d.id; });

        var link = svg.selectAll(".link")
            .data(json.links)
          .enter().append("line")
            .attr("class", "link")
            .attr("stroke-width", function(d) { return d.value; })
            .attr("stroke", "#999");

        link.append("title").text(function(d) {
        var title="";
        for (var i = 0; i < d.alerts.length; i++) {
          title = title + d.alerts[i]['key'] + ": " + d.alerts[i]['doc_count'] + "\n";
        }
        return title;
        });

        var node = svg.selectAll(".node")
            .data(json.nodes)
          .enter().append("g")
            .attr("class", "node")
          .append("circle")
          .attr("r", 4)
          .attr("fill", function(d) { return ((d.type == "source") ? 'red' : 'blue'); })
          .call(force.drag);

        node.append("title")
            .text(function(d) { return d.id; });

        force.on("tick", function() {
          link.attr("x1", function(d) { return d.source.x; })
              .attr("y1", function(d) { return d.source.y; })
              .attr("x2", function(d) { return d.target.x; })
              .attr("y2", function(d) { return d.target.y; });

          //node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });

          node.attr("cx", function (d) { return d.x; }).attr("cy", function (d) { return d.y; });

          group.attr('x', function (d) { return d.bounds.x })
               .attr('y', function (d) { return d.bounds.y })
               .attr('width', function (d) { return d.bounds.width() })
               .attr('height', function(d) { return d.bounds.height() });

          tgroup.attr("x", function(d) { return d.bounds.x + 10; })
	    .attr("y", function(d) { return d.bounds.y + 10; });

        });

        var i = 0;
        setInterval(function() {
            text = "<div class='text-center'><h3 class='title'>"  + json.links[i].source.id + " <span class='glyphicon glyphicon-arrow-right'></span> " + json.links[i].target.id + "</h3></div>"
            //text = text + "<h3 class='title text-center'>Alerts</h3> <ul class='list-group'>";
            text = text + "<ul class='list-group'>";
            d = json.links[i];
            for (var j = 0; j < d.alerts.length; j++) {
                text = text + "<li class='list-group-item'>" + d.alerts[j]['key'] + "<span class='badge'>" + d.alerts[j]['doc_count'] + "</span></li>";
            }
            text = text + "</ul>";
            $("#highlight_info").empty();
            $("#highlight_info").append(text);
            d3.selectAll("circle").data(json.nodes).attr("r", function(d) { if (d.id == json.links[i].source.id || d.id == json.links[i].target.id) return 7; return 4; });
            d3.selectAll("line").data(json.links).attr("stroke", function(d) { if (d == json.links[i]) return "red"; return "#999"; });
            i++;
            if (i >= json.links.length) {
                i = 0;
            }
        }
        , 3000);

      }
      });
}


$( 'document' ).ready(function () { draw_ippair_alerts({{ from_date }}, [{% autoescape off %} {{ probes|join:',' }} {% endautoescape %}], "{{ filter }}"); });

setTimeout(function () { location.reload(); }, {{ reload }} * 1000);

        </script>
    </body>
</html>
